package cn.kgm.makeGodV2.event;

import cn.kgm.makeGodV2.GamePlayer;
import cn.kgm.makeGodV2.WorldState;
import cn.kgm.makeGodV2.trigger.EventTrigger;
import lombok.Builder;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-16 10:37
 * @Description: cn.kgm.makeGodV2.event.GameEvent
 */
@Data
@Builder
public class GameEvent {
    private String id;
    private String name;
    private String description;
    private List<EventTrigger> triggers;
    private List<EventChoice> choices;

    public GameEvent(String id, String name, String description,
                     List<EventTrigger> triggers, List<EventChoice> choices) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.triggers = triggers;
        this.choices = choices;
    }

    public boolean checkTriggers(GamePlayer npc, WorldState worldState) {
        for (EventTrigger trigger : triggers) {
            if (!trigger.checkTrigger(npc, worldState)) {
                return false;
            }
        }
        return true;
    }

    public EventChoice selectChoice(GamePlayer npc) {
        List<EventChoice> availableChoices = new ArrayList<>();
        List<Double> weights = new ArrayList<>();

        // 收集可用选项及其权重
        for (EventChoice choice : choices) {
            if (choice.isAvailable(npc)) {
                availableChoices.add(choice);
                weights.add(choice.getWeight());
            }
        }

        if (availableChoices.isEmpty()) {
            return null;
        }

        // 基于权重的概率选择
        return weightedRandomChoice(availableChoices, weights);
    }

    private EventChoice weightedRandomChoice(List<EventChoice> choices, List<Double> weights) {
        double totalWeight = weights.stream().mapToDouble(Double::doubleValue).sum();
        double random = Math.random() * totalWeight;
        double current = 0;

        for (int i = 0; i < choices.size(); i++) {
            current += weights.get(i);
            if (random <= current) {
                return choices.get(i);
            }
        }

        return choices.get(choices.size() - 1);
    }
}
